#-*-coding:utf-8-*-
#!/usr/bin/python

from lib import config, req_sy, db_sy
from lib import email_sy as email
from lib.logger import logger
from bs4 import BeautifulSoup
import time
import re
import gevent.monkey
gevent.monkey.patch_socket()
import gevent
from gevent.pool import Pool

onlive_src = 'zhanqi'
gpool = Pool(config.GPOOLSIZE)

# 处理来源于战旗的直播视频，直播地址： http://www.zhanqi.tv/swxg
def _pro_onlivedata_from_zhanqi(room_id):
	return 'http://www.zhanqi.tv/live/embed?roomId='+ str(room_id)

def get_data_action(is_get_livedata = True):
	# 战旗视频列表页api:http://www.zhanqi.tv/api/static/live.hots/30-1.json
	# 在线人数作为是否继续爬取的判断条件
	top_views = 101
	page=1
	res_data = []
	game_type = config.ZHANQI_GAME
	while page<=100 and top_views >50:
		# 加入爬取间隙，这个很重要
		if is_get_livedata:
			time.sleep(0.5)
		# top_views 为循环终止条件，因为可能没有查过100页那么多数据
		top_views = 49
		zhanqi_api = config.ZHANQI_API % (page)
		response = req_sy.get_html(zhanqi_api, is_json=True)
		if response and len(response['data']) != 0:
			res_list=response['data']['rooms']
			for zb in res_list:
				kw = {}				
				views = int(zb['online'])
				if views <100:
					continue
				categor = zb['gameName']
				if categor not in game_type:
					continue
				if top_views < views:
					top_views = views
				kw['views'] = views
				kw['zbid'] = zb['id']
				room_id = zb['id']
				vid = zb['id']
				kw['livedata'] = _pro_onlivedata_from_zhanqi(room_id)
				kw['zbname'] = zb['nickname']
				kw['source'] = onlive_src
				kw['views'] = views
				kw['title'] = zb['title']
				kw['category'] = game_type[categor]
				kw['inputtime'] = int(time.time())
				kw['zb_thumb'] = zb['avatar']+"-medium"
				kw['thumb'] = zb['bpic']
					
				res_data.append(kw)
		else:
			logger.error("%s | %s" % ("get "+onlive_src+" API Failed", zhanqi_api))
			email.send_email(onlive_src+u'直播API获取失败', "%s | %s" % ("get ZHANQI API Failed", zhanqi_api))
			top_views = 100
		page=int(page)+1

	return res_data

if __name__ == "__main__":
	now =  time.time()
	dbconn = db_sy.getConnection()
	update_data = get_data_action(is_get_livedata = True)
	db_sy.db_insert(dbconn, update_data)
	dbconn.close()
	print "time cost : " + str(int((time.time() - now))) + " seconds"
